package com.automannn.atm_back.modules.codeGenerator.core.util;

import com.google.common.base.Charsets;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

@Slf4j
public class FreemarkerUtils {

    public static final String CUR_TEMPLATE = "curTemplate";

    private FreemarkerUtils() {
        throw new RuntimeException("禁止创建实例");
    }

    public static String generate(String template, Map<String, Object> map) {
        // 1.创建一个Configuration对象
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 2.设置模板的字符集,一般为utf-8
        configuration.setDefaultEncoding("utf-8");
        //3.在调用时，再将当前模板替换放入模板加载器中
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate(CUR_TEMPLATE, template);
        configuration.setTemplateLoader(stringLoader);

        Template freeMarkerTemplate;
        try {
            // 4.使用Configuration对象,加载一个模板文件,需要指定模板文件的文件名
            freeMarkerTemplate = configuration.getTemplate(CUR_TEMPLATE);
        } catch (IOException e) {
            throw new RuntimeException("未找到模板:" + template);
        }
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Writer out = new OutputStreamWriter(byteArrayOutputStream);
        StringBuilder sb = new StringBuilder();
        try {
            freeMarkerTemplate.process(map, out);
            byte[] result = byteArrayOutputStream.toByteArray();
            return new String(result, Charsets.UTF_8);
        } catch (TemplateException e) {
            log.error("生成失败，模板异常:");
            log.error(e.getMessage());
            sb.append(e.getMessage());
        } catch (IOException e) {
            log.error("生成失败:");
            log.error(e.getMessage());
            sb.append(e.getMessage());
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();

    }
}
